package com.ihomey.linkuphome.ui;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.ihomey.linkuphome.DeviceController;
import com.ihomey.linkuphome.R;
import com.ihomey.linkuphome.base.BaseFragment;
import com.ihomey.linkuphome.util.BindView;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;

import cn.bingoogolapple.qrcode.core.QRCodeView;

import static android.content.Context.VIBRATOR_SERVICE;

/**
 * Created by Administrator on 2017/6/10 0010.
 */

public class ScanFragment extends BaseFragment implements QRCodeView.Delegate {

    private static final String SETTING_LAST_ID = "lastID";
    public static final String IS_SHARE = "isShare";

    @BindView(id = R.id.zxingView)
    private QRCodeView mQRCodeView;
    @BindView(id = R.id.tv_myQRCodeView)
    private TextView myQRCodeView;
    @BindView(id = R.id.tv_scan_hint)
    private TextView tv_scan_hint;

    private MainActivity mainActivity;
    private DeviceController mController;

    public static ScanFragment newInstance() {
        ScanFragment fragment = new ScanFragment();
        return fragment;
    }

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
        return inflater.inflate(R.layout.activity_scan, null);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mainActivity = (MainActivity) activity;
            mController = (DeviceController) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement DeviceController callback interface.");
        }
    }

    @Override
    public void initData() {
        super.initData();
    }

    @Override
    public void initWidget(View parentView) {
        super.initWidget(parentView);
        mainActivity.setTitle(R.string.scan);
        mainActivity.showRightBtn(false);
        mQRCodeView.setDelegate(this);
//        myQRCodeView.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                startActivity(new Intent(ScanActivity.this, ControlShareActivity.class).putExtra("lightType", lightType));
//            }
//        });
    }


    @Override
    public void onStart() {
        super.onStart();
        mQRCodeView.startCamera();
        mQRCodeView.showScanRect();
        mQRCodeView.startSpot();
    }

    @Override
    public void onStop() {
        mQRCodeView.stopCamera();
        super.onStop();
    }

    @Override
    public void onDestroy() {
        mQRCodeView.onDestroy();
        super.onDestroy();
    }

    private void vibrate() {
        Vibrator vibrator = (Vibrator) getActivity().getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        vibrate();
        getRemoteJsonData(result);
    }

    @Override
    public void onScanQRCodeOpenCameraError() {
        Toast.makeText(getActivity(), "打开相机出错", Toast.LENGTH_SHORT).show();
    }

    private void getRemoteJsonData(String dataUrl) {
        mainActivity.showProgressDialog(R.string.getOperationData);
        new HttpUrlGetTask(new I_HttpRespond() {
            @Override
            public void onSuccess(Object t) {
                mainActivity.hideProgressDialog();
                confirmReplacingDatabase(t.toString());
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                mainActivity.hideProgressDialog();
                Toast.makeText(getActivity(), "获取操控分享信息失败，请稍后重试！", Toast.LENGTH_SHORT).show();
            }
        }).execute(dataUrl);
    }


    private void confirmReplacingDatabase(final String json) {
        new MaterialDialog.Builder(getActivity()).content(R.string.confirm_replacing_db).canceledOnTouchOutside(false).negativeText(R.string.cancel).positiveText(R.string.confirm).onPositive(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(MaterialDialog dialog, DialogAction which) {
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            String configuration = URLDecoder.decode(json.toString(), "UTF-8");
                            Log.d("aa", configuration + "---");
                            // read json and set to the database.
                            final boolean success = mController.setConfigurationFromJson(configuration.toString(), mController.getDeviceType());
                            mainActivity.runOnUiThread(new Runnable() {
                                public void run() {
                                    // notify to the user.
                                    Toast.makeText(mainActivity, success ? getString(R.string.import_config_complete) : getString(R.string.import_config_error), Toast.LENGTH_SHORT).show();
                                    mainActivity.setDeviceType(mController.getDeviceType());
                                    mainActivity.onBackPressed();
                                    if (success) {
                                        SharedPreferences activityPrefs = mainActivity.getSharedPreferences("ihomey", Activity.MODE_PRIVATE);
                                        SharedPreferences.Editor editor = activityPrefs.edit();
                                        editor.putBoolean(IS_SHARE + mController.getDeviceType(), true);
                                        editor.commit();
                                    }
                                }
                            });
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        }).build().show();
    }

    /**
     * Restore app settings including devices and groups.
     */
    private void restoreSettings(int settingsID) {
        mController.loadSetting(settingsID);
    }


    public interface I_HttpRespond {
        void onSuccess(Object t);

        void onFailure(Throwable t, int errorNo, String strMsg);
    }


    private class HttpUrlGetTask extends AsyncTask<String, Void, Object> {
        private I_HttpRespond callback;

        public HttpUrlGetTask(I_HttpRespond callback) {
            this.callback = callback;
        }

        @Override
        protected Object doInBackground(String... params) {
            InputStream input = null;
            BufferedReader reader = null;
            StringBuilder respond = null;
            try {
                URL url = new URL(params[0].toString());
                HttpURLConnection conn = (HttpURLConnection) url
                        .openConnection();
                conn.setReadTimeout(5000);
                conn.setConnectTimeout(5000);
//                conn.setRequestProperty("Charset",
//                        config.getCharSet());
                conn.setRequestMethod("GET");
                input = conn.getInputStream();
                reader = new BufferedReader(new InputStreamReader(
                        input));
                int i = 0;
                char[] buf = new char[1024];
                respond = new StringBuilder();
                while ((i = reader.read(buf)) != -1) {
                    respond.append(buf, 0, i);
                }
                conn.disconnect();
            } catch (MalformedURLException e) {
                return e;
            } catch (IOException e) {
                return e;
            } finally {
                closeIO(input, reader);
            }
            return respond;
        }

        @Override
        protected void onPostExecute(Object result) {
            super.onPostExecute(result);
            if (result instanceof MalformedURLException) {
                callback.onFailure((Throwable) result, 3721, "URL错误");
            } else if (result instanceof IOException) {
                callback.onFailure((Throwable) result, 3722, "IO错误");
            } else {
                callback.onSuccess(result);
            }
        }
    }


    /**
     * 关闭流
     *
     * @param closeables
     */
    public static void closeIO(Closeable... closeables) {
        if (null == closeables || closeables.length <= 0) {
            return;
        }
        for (Closeable cb : closeables) {
            try {
                if (null == cb) {
                    continue;
                }
                cb.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
